const { fetchArtworks } = require("../../../utils/request");
const config = require("../../../utils/config");

Page({
  data: {
    selectedOption: "Popular",
    selectedArtistOption: {}, // 艺术家默认选中选项为空
    selectedCategoryOption: {}, // 类别默认选中选项为空
    selectedMovementOption: {}, // 流派默认选中选项为空
    selectedTopicOption: {}, // 话题默认选中选项为空
    PopularOption: false,  //热门选项默认不选中
    artWorkParams: { pageNum: 1, pageSize: 10 }, // 请求的参数
    showDropdown: false, // 下拉菜单是否显示
    currentView: 'grid2',
    isLoading: false, // 防止重复加载
    hasMore: true, // 是否还有更多数据
    pageNum: 1,
    pageSize: 10,
    artworks: [],
    userInfo: null,
    isUserInfoAuthorized: false,
    filters: [],
  },

  onLoad() {
    this.loadArtworks(this.data.artWorkParams);
  },

  onShow() {
    const userInfo = getApp().globalData.userInfo;
    if (!userInfo) {
      wx.redirectTo({ url: "/pages/login/login" });
    }
  },

  async loadArtworks(params) {
    if (this.data.isLoading) return; // 防止重复加载

    this.setData({ isLoading: true });
    try {
      const response = await fetchArtworks(params);
      if (response.data && response.data.list) {
        const updatedArtworks = response.data.list.map((artwork) => ({
          ...artwork,
          primaryImageSmallUrl: `${config.ImageURL}${artwork.primaryImageSmallUrl}`,
        }));
        // this.setData({ artworks: [...this.data.artworks, ...updatedArtworks] });
        this.setData({ 
          artworks: [...this.data.artworks, ...updatedArtworks],
          hasMore: updatedArtworks.length >= this.data.pageSize
         });
      }
    } catch (err) {
      console.error("加载艺术作品失败:", err);
    } finally {
      this.setData({ isLoading: false });
    }
  },
  
  onReachBottom() {
    if (this.data.hasMore && !this.data.isLoading) {
      console.log("加载下一页数据");
      const newPageNum = this.data.pageNum + 1; // 页码加1
      this.setData({ 
        pageNum: newPageNum, 
        'artWorkParams.pageNum': newPageNum // 更新 artWorkParams 的 pageNum
      });
      // 更新请求的参数数据
      console.log("当前的页数：" + this.data.pageNum); // 使用 this.data.pageNum 打印
      console.log("当前的artWorkParams的请求参数数据：" + JSON.stringify(this.data.artWorkParams));
      this.loadArtworks(this.data.artWorkParams); // 加载下一页数据
    }
  },

  switchView: function (e) {
    this.setData({
      currentView: e.currentTarget.dataset.view
    });
  },

  selectedParam() {
    console.log("开始选择根据参数进行查找");
    wx.navigateTo({
      url: "/pages/filter/filter/filter", // 跳转到用户根据选项进行查找页面
      events: {
        acceptDataFromChild: (data) => {
          console.log("从过滤页面接收到的数据:", data);
          this.setData({
            selectedArtistOption: data.selectedArtistOption || {}, // 更新父页面的数据
            selectedCategoryOption: data.selectedCategoryOption || {}, // 更新父页面的数据
            selectedMovementOption: data.selectedMovementOption || {}, // 更新父页面的数据
            selectedTopicOption: data.selectedTopicOption || {}, // 更新父页面的数据
            PopularOption: data.PopularOption || false,  // 更新父页面的数据
          });

          // 重置页码
          this.setData({
            pageNum: 1, // 从第1页开始
          });

          // 声明变量
          let selectedOptionName = "Multiple Select";
          let topicId = null;
          let categoryId = null;
          let artistId = null;
          let movementId = null;
          let i = 0; // 统计不为空的数据个数

          // 检查接收到的数据中是否有不为空的选项
          if (
            data.selectedArtistOption?.id ||
            data.selectedCategoryOption?.id ||
            data.selectedMovementOption?.id ||
            data.selectedTopicOption?.id
          ) {
            if (data.selectedArtistOption?.id) {
              i++;
              artistId = data.selectedArtistOption.id;
              selectedOptionName = data.selectedArtistOption.artistName;
            }
            if (data.selectedCategoryOption?.id) {
              i++;
              categoryId = data.selectedCategoryOption.id;
              selectedOptionName = data.selectedCategoryOption.categoryName;
            }
            if (data.selectedMovementOption?.id) {
              i++;
              movementId = data.selectedMovementOption.id;
              selectedOptionName = data.selectedMovementOption.movementName;
            }
            if (data.selectedTopicOption?.id) {
              i++;
              topicId = data.selectedTopicOption.id;
              selectedOptionName = data.selectedTopicOption.topicName;
            }

            // 根据选中选项数量更新 `selectedOption`
            this.setData({
              selectedOption: i === 1 ? selectedOptionName : "Multiple Select",
            });
          } else {
            // 用户只选择了 Popular 选项
            this.setData({
              selectedOption: "Popular", // 重新修改用户的选项
            });
          }

          // 构造请求参数
          const ArtWorkReqDto = {
            topicId: topicId,
            categoryId: categoryId, // 修正这里的错误，之前是 categoryId: topicId
            artistId: artistId,
            movementId: movementId,
            pageNum: this.data.pageNum,
            pageSize: this.data.pageSize,
          };
          console.log("用户总的一个选项：" + JSON.stringify(ArtWorkReqDto));

          // 更新请求参数和清空以前的数据
          this.setData({
            artWorkParams: ArtWorkReqDto, // 更新请求的参数
            artworks: [], // 清空以前的数据
            leftColumn: [], // 清空以前的数据
            rightColumn: [], // 清空以前的数据
          });

          // 发送请求 按照新的条件进行查找
          this.loadArtworks(this.data.artWorkParams);
        },
      },
      success: (res) => {
        // 使用 eventChannel 传递数据
        res.eventChannel.emit("sendDataToChild", {
          selectedArtistOption: this.data.selectedArtistOption,
          selectedCategoryOption: this.data.selectedCategoryOption,
          selectedMovementOption: this.data.selectedMovementOption,
          selectedTopicOption: this.data.selectedTopicOption,
          PopularOption: this.data.PopularOption,
        });
      },
    });
  },

  setGridView1(e) {
    console.log("矩阵图setGridView1-----");
    this.switchView(e);
  },
  setGridView2(e) {
    console.log("矩阵图setGridView2-----");
    this.switchView(e);
  },
  setListView(e) {
    console.log("列表setListView-----");
    this.switchView(e);
  },

  goToDetail(e) {
    const artWorkId = e.currentTarget.dataset.id;
    console.log("正在跳转到艺术画id为：" + artWorkId)
    wx.navigateTo({
      url: `/pages/artwork/detail/detail?artWorkId=${artWorkId}`
    });
  }
});
